package com.car.loan.project.system.service.impl;

import com.car.loan.project.system.domain.SysSequence;
import com.car.loan.project.system.mapper.SysSequenceMapper;
import com.car.loan.project.system.service.ISysSequenceService;
import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huangding
 * @description
 * @date 2019/10/28 20:19
 */
@Service
public class SequenceBusinessServiceImpl implements ISysSequenceService {

    @Autowired
    private SysSequenceMapper sysSequenceMapper;

    /**
     * 业务编号规则 CDYYYY-XXXXX，YYYY为年分，XXXXX为五位数从00001开始向上累加，如跨年了，重新从00001开始业务编号规则
     */
    @Override
    public synchronized String next() {
        SysSequence sysSequence = sysSequenceMapper.selectById(1);
        int oldYear = Integer.parseInt(sysSequence.getYear());
        int currentYear = LocalDate.now().getYear();
        int value = sysSequence.getValue();
        value = value + 1;
        if (currentYear > oldYear) {
            sysSequence.setYear(String.valueOf(currentYear));
            value = 1;
        }
        sysSequence.setValue(value);
        sysSequenceMapper.updateById(sysSequence);
        return sysSequence.getPrefix() + currentYear + "-" + String.format("%05d", value);
    }

}
